package com.wusuowei.checkcode.controller;

import com.wusuowei.common.core.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Api(value = "邮箱验证码服务接口",tags = "邮箱验证码服务接口")
@RestController
@RequestMapping("email")
public class EmailController {

    @Autowired
    private JavaMailSender javaMailSender;
    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.muban}")
    private String muban;
    @Value("${spring.mail.outTime}")
    private String outTime;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value="发送邮箱", notes="生成验证信息")
    @GetMapping("/sendEmail/{emailReceiver}")
    public String sendSimpleMail(@PathVariable String emailReceiver) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(emailReceiver);
        // 设置邮件的主题
        message.setSubject("登录验证码");
        // 设置邮件的正文
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        String format = String.format(muban, code,outTime);
        message.setText(format);
        // 发送邮件
        try {
            javaMailSender.send(message);
            redisCache.setCacheObject(emailReceiver,code.toString(),Integer.valueOf(outTime), TimeUnit.MINUTES);
            return "发送成功";
        } catch (MailException e) {
            e.printStackTrace();
        }
        return "发送失败";
    }

}
